package stack;

import stack.stackDefine.MyArrayListStack;

/**
 * 栈计算中缀表达式 ---
 * 只能简单 + - * / and  发现一个特殊例子： 5-5/5-1
 * 于是我优化了一下减法的操作
 */
public class CalStack {
    public static void main(String[] args) {
        String str = "5-5/5-1"; //中缀表达式
        // 创建二个栈，数栈，一个符号栈
        MyArrayListStack<Integer> numStack = new MyArrayListStack<>();
        MyArrayListStack<Integer> operStack = new MyArrayListStack<>();
        int index = 0; //遍历
        int num1 = 0;
        int num2 = 0;
        int oper = 0;
        int res = 0;
        char ch = ' '; // 将每次扫描得到的ch保存到
        String keepNum = ""; // 保存长的数字
        while (true){
            // 依次得到str的每一个字节
             ch = str.charAt(index);
             if(operStack.isOper(ch)){
                 // 判断当前符号栈是不是为空
                 if (operStack.isNotEmpty()){
                     if (operStack.priority(ch)<=operStack.priority(operStack.peek())){
                         if (ch=='-'&& operStack.peek()=='-'){
                             ch = '+';
                         }
                         num1 = numStack.pop();
                         num2 = numStack.pop();
                         oper = operStack.pop();
                         res = numStack.cal(num1,num2, (char) oper);
                         numStack.push(res);
                         operStack.push((int) ch);
                     }else {
                         operStack.push((int) ch);
                     }
                 }else{
                     operStack.push((int) ch);
                 }
             }else {
                 keepNum+=ch;
                 // 如果ch已经是str的最后一位，就直接入栈
                 if (index==str.length()-1){
                     numStack.push(Integer.parseInt(keepNum));
                 }else {
                     if(operStack.isOper(str.charAt(index+1))){
                         // 后一位是操作符
                         numStack.push(Integer.parseInt(keepNum));
                         keepNum = "";
                     }
                 }
                 //numStack.push(Integer.parseInt(String.valueOf(ch)));
             }
             index+=1;
             if (index==str.length()){
                 break;
             }
        }
        while (true){
            if (operStack.empty()){
                break;
            }
                num1 = numStack.pop();
                num2 = numStack.pop();
                System.out.println(operStack.getLength());
                oper = operStack.pop();
                if (oper=='-' && operStack.getLength()!=0 &&  operStack.peek()=='-') {
                    oper ='+';
                }
                res = numStack.cal(num1,num2, (char) oper);
                numStack.push(res);
        }
        System.out.println("表达式为："+numStack.pop());
    }
}
